import { ApiArticles, Channel } from '@/types/data'
import { homeAction } from '@/types/store'

/* eslint-disable camelcase */
type T = {
  userChannel: Channel[],
  active: string,
  allChannel: Channel[],
  channelArticles: {[key:string]:{
    timestamp:string|undefined,
    articles:ApiArticles[]
  }}
}
const initialState:T = {
  userChannel: [],
  active: '0', // 当前被高亮的频道编号
  allChannel: [],
  channelArticles: {
    0: {
      timestamp: undefined,
      articles: []
    }
  }
} as T

const home = (state:T = initialState, action: homeAction) => {
  if (action.type === 'home/getUserChannel') {
    return { ...state, userChannel: action.payload }
  } else if (action.type === 'home/changeChannel') {
    return { ...state, active: action.id }
  } else if (action.type === 'home/getAllChannel') {
    return { ...state, allChannel: action.payload }
  } else if (action.type === 'home/getArticles') {
    const { channel_id, pre_timestamp, results } = action.payload
    const articles = state.channelArticles[channel_id]?.articles || []
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          timestamp: pre_timestamp,
          articles: [...articles, ...results]
        }
      }
    }
  } else if (action.type === 'home/booleanArticles') {
    const { channel_id, pre_timestamp, results } = action.payload
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          timestamp: pre_timestamp,
          articles: results
        }
      }
    }
  }
  return state
}

export default home
